Hydra
Table of Content
Hydra#
Hydra is an open-source Python framework that simplifies the development of research and other complex applications. The key feature is the ability to dynamically create a hierarchical configuration by composition and override it through config files and the command line.
Demo#
- Load config from
yamlfile - Convert yaml config to typed object using dataclass
- Override
yamldata from CLI
config.yaml
db:
driver: mysql
table: bar
user: bar
password: foo
map yaml file to typed object using dataclass
@dataclass
class DB:
driver: str
table: str
user: str
password: str
@dataclass
class Settings:
db: DB
cs = ConfigStore.instance()
# name `base_config` is used for matching it with the main.yaml's default section
cs.store(name="base_config", node=Settings)
full example
import cv2
import hydra
# from omegaconf import DictConfig, OmegaConf
from hydra.core.config_store import ConfigStore
from dataclasses import dataclass
@dataclass
class DB:
driver: str
table: str
user: str
password: str
@dataclass
class Settings:
db: DB
cs = ConfigStore.instance()
# name `base_config` is used for matching it with the main.yaml's default section
cs.store(name="base_config", node=Settings)
@hydra.main(config_path=".", config_name="config", version_base="1.1")
def my_app(cfg: Settings) -> None:
# print(OmegaConf.to_yaml(cfg))
print(cfg)
print(type(cfg))
print(cfg.db.driver)
print(cfg.db.table)
if __name__ == "__main__":
my_app()